//
//  AddEduExpViewController.m
//  CYWFrame
//
//  Created by 于顺燊 on 2018/9/18.
//  Copyright © 2018年 Macx. All rights reserved.
//

#import "AddEduExpViewController.h"
#import "WSDatePickerView.h"

@interface AddEduExpViewController ()<UITextFieldDelegate, UITextViewDelegate, UIPickerViewDelegate, UIPickerViewDataSource>

@property (strong, nonatomic) UIScrollView *scrollView;
@property (strong, nonatomic) NSString *startDate;
@property (strong, nonatomic) NSString *endDate;
@property (strong, nonatomic) UIPickerView *educationPicker;
@property (strong, nonatomic) NSArray *educationInfoArr;
@property (strong, nonatomic) UIView *pickerBgView;
@property (strong, nonatomic) UIView *pickerToolbgView;

@end

@implementation AddEduExpViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
	self.view.backgroundColor = UISeparatedColorRGB;
	[self createUI];
}

- (void)createUI {
	if (self.type == 1) {
		UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
		[deleteBtn addTarget:self action:@selector(deleteEduExpInfo)forControlEvents:UIControlEventTouchUpInside];
		[deleteBtn setTitle:@"删除经历" forState:UIControlStateNormal];
		[deleteBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
		[deleteBtn setTintColor:kWhiteColor];
		UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:deleteBtn];
		self.navigationItem.rightBarButtonItem = rightItem;
		self.navigationItem.title = @"编辑教育经历";
	}
	else {
		self.navigationItem.title = @"添加教育经历";
	}
	
	_scrollView.backgroundColor = UISeparatedColorRGB;
	_scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
	[self.view addSubview:_scrollView];
	NSArray *arr = [NSArray arrayWithObjects:@"   开始时间", @"   结束时间", @"   学校名称", @"   学位", @"   专业", nil];
	
	CGSize size = [LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(15)];
	
	for (int i = 0; i < arr.count; i++) {
		UILabel *label = [[UILabel alloc] init];
		[_scrollView addSubview:label];
		label = [self createLabel:label text:arr[i]];
		label.tag = 1+i;
	}
	
	//工作开始时间
	UILabel *startDateL = [self.view viewWithTag:1];
	startDateL.frame = CGRectMake(0, 10, SCREEN_WIDTH, size.height+30);
	
	UITextField *startDateF = [[UITextField alloc] initWithFrame:CGRectMake(30+size.width, startDateL.y, SCREEN_WIDTH-(50+size.width), size.height+30)];
	[_scrollView addSubview:startDateF];
	startDateF.delegate = self;
	startDateF.textColor = kGrayColor;
	startDateF.clearButtonMode = UITextFieldViewModeWhileEditing;
	startDateF.font = kUHSystemFontWithSize(15);
	startDateF.textAlignment = NSTextAlignmentRight;
	startDateF.rightViewMode = UITextFieldViewModeAlways;
	startDateF.tag = 11;
	UIImageView *imgV1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, size.height/2, size.height)];
	startDateF.rightView = imgV1;
	imgV1.image = IMAGE(@"arrow_right_grey");
	NSString *startTimeStr = self.info[@"start_time"];
	self.startDate = startTimeStr;
	if (startTimeStr.length >= 8) {
		NSString *yearStr = [startTimeStr substringWithRange:NSMakeRange(0, 4)];
		NSString *monthStr = [startTimeStr substringWithRange:NSMakeRange(4, 2)];
		NSString *dayStr = [startTimeStr substringWithRange:NSMakeRange(6, 2)];
		startDateF.text = [NSString stringWithFormat:@"%@年%@月%@日", yearStr, monthStr, dayStr];
	}
	
	UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(startDateF.x, startDateF.y, startDateF.width, startDateF.height)];
	[_scrollView addSubview:view1];
	[view1 addActionWithblock:^{
		NSLog(@"选择开始时间");
		[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
		// 显示日期选择
		WSDatePickerView *datepicker = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDay CompleteBlock:^(NSDate *selectDate) {
			
			//            NSString *date = [selectDate stringWithFormat:@"yyyy-MM-dd"];
			NSString *date = [NSString stringWithFormat:@"%ld年%ld月%ld日",selectDate.year,selectDate.month,selectDate.day];
			startDateF.text = date;
			self.startDate = [NSString stringWithFormat:@"%ld%02ld%02ld",selectDate.year,selectDate.month,selectDate.day];
		}];
		
		NSDateFormatter *minDateFormater = [[NSDateFormatter alloc] init];
		[minDateFormater setDateFormat:@"yyyy-MM-dd"];
		NSDate *scrollToDate = [minDateFormater dateFromString:@"1930-1-1"];
		datepicker.minLimitDate = scrollToDate;
		datepicker.maxLimitDate = [NSDate date];
		[datepicker show];
	}];
	
	//结束时间
	UILabel *endDateL = [self.view viewWithTag:2];
	endDateL.frame = CGRectMake(0, startDateL.y+startDateL.height+1, SCREEN_WIDTH, size.height+30);
	
	UITextField *endDateF = [[UITextField alloc] initWithFrame:CGRectMake(30+size.width, endDateL.y, SCREEN_WIDTH-(50+size.width), size.height+30)];
	[_scrollView addSubview:endDateF];
	endDateF.delegate = self;
	endDateF.textColor = kGrayColor;
	endDateF.clearButtonMode = UITextFieldViewModeWhileEditing;
	endDateF.font = kUHSystemFontWithSize(15);
	endDateF.textAlignment = NSTextAlignmentRight;
	endDateF.rightViewMode = UITextFieldViewModeAlways;
	endDateF.tag = 12;
	UIImageView *imgV2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, size.height/2, size.height)];
	endDateF.rightView = imgV2;
	imgV2.image = IMAGE(@"arrow_right_grey");
	NSString *endTimeStr = self.info[@"end_time"];
	NSLog(@"教育经历结束时间%@",endTimeStr);
	self.endDate = endTimeStr;
	if (endTimeStr.length >= 8) {
		NSString *yearStr2 = [endTimeStr substringWithRange:NSMakeRange(0, 4)];
		NSString *monthStr2 = [endTimeStr substringWithRange:NSMakeRange(4, 2)];
		NSString *dayStr2 = [endTimeStr substringWithRange:NSMakeRange(6, 2)];
		endDateF.text = [NSString stringWithFormat:@"%@年%@月%@日", yearStr2, monthStr2, dayStr2];
	}
	UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(endDateF.x, endDateF.y, endDateF.width, endDateF.height)];
	[_scrollView addSubview:view2];
	[view2 addActionWithblock:^{
		NSLog(@"选择结束时间");
		[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
		// 显示日期选择
		WSDatePickerView *datepicker = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDay CompleteBlock:^(NSDate *selectDate) {
			
			//            NSString *date = [selectDate stringWithFormat:@"yyyy-MM-dd"];
			NSString *date = [NSString stringWithFormat:@"%ld年%ld月%ld日",selectDate.year,selectDate.month,selectDate.day];
			endDateF.text = date;
			self.endDate = [NSString stringWithFormat:@"%ld%02ld%02ld",selectDate.year,selectDate.month,selectDate.day];
		}];
		
		NSDateFormatter *minDateFormater = [[NSDateFormatter alloc] init];
		[minDateFormater setDateFormat:@"yyyy-MM-dd"];
		NSDate *scrollToDate = [minDateFormater dateFromString:@"1930-1-1"];
		datepicker.minLimitDate = scrollToDate;
		datepicker.maxLimitDate = [NSDate date];
		[datepicker show];
	}];
	
	//学校名称
	UILabel *universityL = [self.view viewWithTag:3];
	universityL.frame = CGRectMake(0, endDateL.y+endDateL.height+1, SCREEN_WIDTH, size.height+30);
	
	UITextField *universityF = [[UITextField alloc] initWithFrame:CGRectMake(30+size.width, universityL.y, SCREEN_WIDTH-(50+size.width), size.height+30)];
	[_scrollView addSubview:universityF];
	universityF.delegate = self;
	universityF.textColor = kGrayColor;
	universityF.clearButtonMode = UITextFieldViewModeWhileEditing;
	universityF.font = kUHSystemFontWithSize(15);
	universityF.textAlignment = NSTextAlignmentRight;
	universityF.rightViewMode = UITextFieldViewModeAlways;
	universityF.tag = 13;
	universityF.text = self.info[@"title"];
	UIImageView *imgV3 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, size.height/2, size.height)];
	universityF.rightView = imgV3;
	imgV3.image = IMAGE(@"arrow_right_grey");
	
	//学位
	UILabel *degreeL = [self.view viewWithTag:4];
	degreeL.frame = CGRectMake(0, universityL.y+universityL.height+1, SCREEN_WIDTH, size.height+30);
	
	UITextField *degreeF = [[UITextField alloc] initWithFrame:CGRectMake(30+size.width, degreeL.y, SCREEN_WIDTH-(50+size.width), size.height+30)];
	[_scrollView addSubview:degreeF];
	degreeF.delegate = self;
	degreeF.textColor = kGrayColor;
	degreeF.clearButtonMode = UITextFieldViewModeWhileEditing;
	degreeF.font = kUHSystemFontWithSize(15);
	degreeF.textAlignment = NSTextAlignmentRight;
	degreeF.rightViewMode = UITextFieldViewModeAlways;
	degreeF.tag = 14;
	degreeF.text = self.info[@"education"];
	UIImageView *imgV4 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, size.height/2, size.height)];
	degreeF.rightView = imgV4;
	imgV4.image = IMAGE(@"arrow_right_grey");
	UIView *view4 = [[UIView alloc] initWithFrame:CGRectMake(degreeF.x, degreeF.y, degreeF.width, degreeF.height)];
	[_scrollView addSubview:view4];
	[view4 addActionWithblock:^{
		NSLog(@"选择学历");
		[self pickerShow:4];
		
	}];
	
	//专业
	UILabel *majorL = [self.view viewWithTag:5];
	majorL.frame = CGRectMake(0, degreeL.y+degreeL.height+1, SCREEN_WIDTH, size.height+30);
	
	UITextField *majorF = [[UITextField alloc] initWithFrame:CGRectMake(30+size.width, majorL.y, SCREEN_WIDTH-(50+size.width), size.height+30)];
	[_scrollView addSubview:majorF];
	majorF.delegate = self;
	majorF.textColor = kGrayColor;
	majorF.clearButtonMode = UITextFieldViewModeWhileEditing;
	majorF.font = kUHSystemFontWithSize(15);
	majorF.textAlignment = NSTextAlignmentRight;
	majorF.rightViewMode = UITextFieldViewModeAlways;
	majorF.tag = 15;
	majorF.text = self.info[@"major"];
	UIImageView *imgV5 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, size.height/2, size.height)];
	majorF.rightView = imgV5;
	imgV5.image = IMAGE(@"arrow_right_grey");
	
	
	_pickerBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
	[self.view addSubview:_pickerBgView];
	_pickerBgView.backgroundColor = RGBA(0, 0, 0, 0.2);
	_pickerBgView.hidden = YES;
	
	_educationInfoArr = @[@"初中及以下", @"中专/中技", @"高中", @"大专", @"本科", @"硕士", @"博士"];
	_educationPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 2*SCREEN_HEIGHT, SCREEN_WIDTH, SH(2.5))];
	[self.view addSubview:_educationPicker];
	_educationPicker.delegate = self;
	_educationPicker.dataSource = self;
	_educationPicker.backgroundColor = UISeparatedColorRGB;
	_educationPicker.showsSelectionIndicator = YES;
	_educationPicker.hidden = YES;
	
	_pickerToolbgView = [[UIView alloc] initWithFrame:CGRectMake(0, 2*SCREEN_HEIGHT, SCREEN_WIDTH, 40)];
	[self.view addSubview:_pickerToolbgView];
	_pickerToolbgView.backgroundColor = UISeparatedColorRGB;
	
	NSArray *arr2 = @[@"取消", @"确定"];
	for (int i = 0; i < arr2.count; i++) {
		UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
		[_pickerToolbgView addSubview:btn];
		[btn setTitle:arr2[i] forState:UIControlStateNormal];
		[btn setTitleColor:kBlackColor forState:UIControlStateNormal];
		btn.titleLabel.font = kUHSystemFontWithSize(12);
		if (i==0) {
			btn.frame = CGRectMake(0, 0, 50, 40);
			[btn addTarget:self action:@selector(pickerRemove) forControlEvents:UIControlEventTouchUpInside];
		}
		else {
			btn.frame = CGRectMake(SCREEN_WIDTH-50, 0, 50, 40);
			[btn addTarget:self action:@selector(priceBtnText) forControlEvents:UIControlEventTouchUpInside];
		}
	}
	UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 39, SCREEN_WIDTH, 1)];
	[_pickerToolbgView addSubview:line];
	line.backgroundColor = kLightGrayColor;
	
	
	//保存按钮
	UIButton *saveBtn = [[UIButton alloc] initWithFrame:CGRectMake( 30, majorL.y+majorL.height+20,  SCREEN_WIDTH-30*2, 40)];
	saveBtn.layer.cornerRadius = saveBtn.height/4;
	[saveBtn setTitle:@"保存" forState:UIControlStateNormal];
	[saveBtn setBackgroundColor:UIMainColorRGB];
	[saveBtn addTarget:self action:@selector(addEduExp) forControlEvents:UIControlEventTouchUpInside];
	[_scrollView addSubview:saveBtn];
	
	_scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, saveBtn.y+saveBtn.height+20);
}

#pragma mark ==========UIPickerView==========
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pickerView
{
	//    return 2; // 返回1表明该控件只包含1列
	
	if ([pickerView isEqual:_educationPicker]) {
		return 1;
	}
	else {
		return 2;
	}
}
//UIPickerViewDataSource中定义的方法，该方法的返回值决定该控件指定列包含多少个列表项
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	// 由于该控件只包含一列，因此无须理会列序号参数component
	// 该方法返回books.count，表明books包含多少个元素，该控件就包含多少行
	//    return self.pickerArr.count;
	if([pickerView isEqual:_educationPicker]){
		return self.educationInfoArr.count;
	}
	else {
		return 0;
	}
}
// UIPickerViewDelegate中定义的方法，该方法返回的NSString将作为UIPickerView
// 中指定列和列表项的标题文本
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
	// 由于该控件只包含一列，因此无须理会列序号参数component
	// 该方法根据row参数返回books中的元素，row参数代表列表项的编号，
	// 因此该方法表示第几个列表项，就使用books中的第几个元素
	//    return [self.pickerArr objectAtIndex:row];
	if([pickerView isEqual:_educationPicker]) {
		return self.educationInfoArr[row];
	}
	else{
		return @"";
	}
}

- (void)pickerShow:(NSInteger)picker {
	[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
	if(picker == 4){
		_educationPicker.hidden = NO;
		_pickerBgView.hidden = NO;
		[UIView animateWithDuration:0.33 animations:^{
			_pickerToolbgView.y = SH(3)*2-94;
			_educationPicker.y = SH(3)*2-94;
		} completion:^(BOOL finished) {
		}];
	}
}
- (void)priceBtnText {
	
	if(_educationPicker.isHidden == NO)
	{
		UITextField *textField = [self.view viewWithTag:14];
		textField.text = self.educationInfoArr[[_educationPicker selectedRowInComponent:0]];
		[self pickerRemove];
	}
}
- (void)pickerRemove {
	
	[UIView animateWithDuration:0.33 animations:^{
		_pickerToolbgView.y = 2*SCREEN_HEIGHT;
		_educationPicker.y = 2*SCREEN_HEIGHT;
	} completion:^(BOOL finished) {
		_pickerBgView.hidden = YES;
		_educationPicker.hidden = YES;
	}];
}

- (UILabel *)createLabel:(UILabel *)label text:(NSString *)text {
	
	label.textColor = [UIColor grayColor];
	label.text = text;
	label.font = kUHSystemFontWithSize(15);
	label.backgroundColor = kWhiteColor;
	return label;
}

- (void)addEduExp
{
	UITextField *startTF = (UITextField *)[self.view viewWithTag:11];
	UITextField *endTF = (UITextField *)[self.view viewWithTag:12];
	UITextField *universityTF = (UITextField *)[self.view viewWithTag:13];
	UITextField *degreeTF = (UITextField *)[self.view viewWithTag:14];
	UITextField *majorTF = (UITextField *)[self.view viewWithTag:15];
	
	NSArray *arr = @[startTF, endTF, universityTF, degreeTF, majorTF];
	for(UITextField *tf in arr)
	{
		if ([NSString isEmpty:tf.text]) {
			[self presentViewController:[LZCTools alertMessage:@"信息不能为空，请填写完所有信息后再次提交"] animated:YES completion:nil];
			return;
		}
	}
	if (self.type == 0) {
		NSLog(@"resume_id is %@", self.resumeId);
		NSDictionary *param = @{
								@"resume_id":self.resumeId,
								@"title":universityTF.text,
								@"start_time":self.startDate,
								@"end_time":self.endDate,
								@"education":degreeTF.text,
								@"major":majorTF.text
								};
		[[NetworkTool sharedTool] requestWithName:@"添加教育经历" URLString:APIAddEduExp parameters:param method:@"POST" callBack:^(id responseObject) {
			NSString *resultState = responseObject[@"data"][@"status"];
			if ([resultState integerValue] == 1) {
				UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"添加成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
				[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
					[self.navigationController popViewControllerAnimated:YES];
				}]];
				[self presentViewController:alert animated:YES completion:nil];
			}
		}];
	}
	else {
		NSDictionary *param = @{
								@"id":self.info[@"id"],
								@"resume_id":self.resumeId,
								@"title":universityTF.text,
								@"start_time":self.startDate,
								@"end_time":self.endDate,
								@"education":degreeTF.text,
								@"major":majorTF.text
								};
		[[NetworkTool sharedTool] requestWithName:@"编辑教育经历" URLString:APIUpdateEduExp parameters:param method:@"POST" callBack:^(id responseObject) {
			NSString *resultState = responseObject[@"data"][@"status"];
			UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"编辑成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
			[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
				[self.navigationController popViewControllerAnimated:YES];
			}]];
			[self presentViewController:alert animated:YES completion:nil];
		}];
	}
}

- (void)deleteEduExpInfo {
	UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定删除？" message:nil preferredStyle:UIAlertControllerStyleAlert];
	[alert addAction:[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
	}]];
	[alert addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
		NSDictionary *param = @{
								@"resume_id":self.resumeId,
								@"del_id":self.info[@"id"],
								@"type":@"2"
								};
		[[NetworkTool sharedTool] requestWithName:@"删除教育经历" URLString:APIDeleteExpInfo parameters:param method:@"POST" callBack:^(id responseObject) {
			UIAlertController *actionSuccessAlert = [UIAlertController alertControllerWithTitle:@"删除成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
			[actionSuccessAlert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
				[self.navigationController popViewControllerAnimated:YES];
			}]];
			[self presentViewController:actionSuccessAlert animated:YES completion:nil];
		}];
	}]];
	[self presentViewController:alert animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
